package org.git.movie.interceptors;

import com.alibaba.fastjson.JSON;
import org.git.movie.entity.PerfLog;
import org.git.movie.filters.TraceIdFilter;
import org.git.movie.util.IpUtil;
import org.git.movie.vo.PerfLogWrap;
import org.perf4j.LoggingStopWatch;
import org.perf4j.StopWatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sqyc
 */
public class PerformanceInterceptor  extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger("org.perf4j.TimingLogger");
    public static ThreadLocal<PerfLogWrap> local = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        PerfLogWrap perfLogWrap = new PerfLogWrap();
        PerfLog perfLog = new PerfLog("url");


        String traceId = MDC.get(TraceIdFilter.TRACE_KEY);
        String requestUrl = request.getRequestURI().toString();
        String clientIp = IpUtil.getIp(request);
        String userAgent = request.getHeader("User-Agent");
        perfLog.setTraceId(traceId);
        perfLog.setUrl(requestUrl);
        perfLog.setClientIp(clientIp);
        perfLog.setUserAgent(userAgent);

        perfLogWrap.setPerfLog(perfLog);

        StopWatch stopWatch = new LoggingStopWatch(requestUrl);
        stopWatch.start(requestUrl);
        perfLogWrap.setWatch(stopWatch);
        perfLogWrap.setStart(System.currentTimeMillis());

        local.set(perfLogWrap);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        PerfLogWrap perfLogWrap = local.get();

        if (perfLogWrap != null) {
            PerfLog perfLog = perfLogWrap.getPerfLog();

            StopWatch watch = perfLogWrap.getWatch();
            watch.stop();

            long end = System.currentTimeMillis();
            long exeTime = end - perfLogWrap.getStart();
            perfLog.setTakeTime(exeTime);

            local.remove();
            logger.info("耗时打印 =  "  +JSON.toJSONString(perfLog));



        }

    }


}
